//
//  SHCountDownListManager.swift
//  SHCountDown
//
//  Created by jiaxing liu on 2019/1/25.
//  Copyright © 2019 jiaxing liu. All rights reserved.
//

import UIKit

class SHCountDownListManager: NSObject {
    
   fileprivate var taleView:UITableView?
    
   fileprivate var dateArray:[Double]?
    
   fileprivate var timer:DispatchSourceTimer?
    
    override init() {
        super.init()
    }
    
    convenience init(tableView:UITableView ,dataArray:[Double]) {
        self.init()
        
        self.taleView  = tableView
        self.dateArray = dataArray
        
        setCountDown()
        
    }
    
    func setCountDown() {
        if timer != nil {
            return
        }
        let queue = DispatchQueue.global()
        timer     = DispatchSource.makeTimerSource(queue:queue)
        timer?.schedule(wallDeadline: .now(),repeating:.seconds(1))
        timer?.setEventHandler { [weak self] in
            DispatchQueue.main.async(execute: {
                guard let cells = self?.taleView?.visibleCells else { return }
                guard let dateArray = self?.dateArray else { return }
                for cell in cells {
                    guard let cell = cell as? CountDownCell else { return }
                    cell.dateView.endTime = dateArray[cell.tag]
                }
            })
            
        }
        timer?.resume()
    }
    
    func destroyTimer() {
        if timer != nil {
            timer?.cancel()
            timer = nil
        }
    }
}
